package com.hzhk.happyrent.ui.view;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;


import java.util.Hashtable;

/**
 * 此控件为自动换行控件
 *
 * @author feizhao2
 */
public class PredicateLayout extends LinearLayout {
    int mLeft, mRight, mTop, mBottom;
    Hashtable<View, Position> map = new Hashtable<View, Position>();
    private static int DEFAULT_DIVIDORCOL = 24;

    /**
     * 每个view上下的间距
     */
    private int dividerLine = 20;
    /**
     * 每个view左右的间距
     */
    private int dividerCol = DEFAULT_DIVIDORCOL;

    public PredicateLayout(Context context) {
        super(context);
        dividerLine = dip2px(getContext(), 8);
        DEFAULT_DIVIDORCOL = dip2px(getContext(), 4);
    }

    public PredicateLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public PredicateLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @Override
    protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {

        int mWidth = MeasureSpec.getSize(widthMeasureSpec);
        int mCount = getChildCount();
        // int mX = 0;
        // int mY = 0;
        mLeft = 0;
        mRight = 0;
        mTop = 10;
        mBottom = 0;

        int j = 0;

        boolean isFirstRow = true;

        for (int i = 0; i < mCount; i++) {
            final View child = getChildAt(i);
            child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
            // 此处增加onlayout中的换行判断，用于计算所需的高度
            int childw = child.getMeasuredWidth();
            int childh = child.getMeasuredHeight();

            mRight += childw; // 将每次子控件宽度进行统计叠加，如果大于设定的宽度则需要换行，高度即Top坐标也需重新设置

            Position position = new Position();
            mLeft = getPosition(i - j, i);
            mRight = mLeft + child.getMeasuredWidth();
            if (mRight >= mWidth) {//超过一行则进行换行同时对每个child间隙进行平均分配
                // mX = childw;
                // mY += childh;
                //				if (isFirstRow) {
                //					dividerCol = (int)((mWidth - child.getMeasuredWidth() * i*1.0) / (i+1)+0.5);
                //					isFirstRow = false;
                //					for (int k = 0; k < i; k++) {
                //						View tempChild = getChildAt(k);
                //						Position p = map.get(tempChild);
                //						p.left += dividerCol - DEFAULT_DIVIDORCOL;
                //						p.right += dividerCol - DEFAULT_DIVIDORCOL;
                //					}
                //				}

                j = i;
                mLeft = getPaddingLeft() + dividerCol - DEFAULT_DIVIDORCOL;
                mRight = mLeft + child.getMeasuredWidth();
                mTop += childh + dividerLine;
                // PS：如果发现高度还是有问题就得自己再细调了
            }
            mBottom = mTop + child.getMeasuredHeight();
            // mY = mTop; //每次的高度必须记录 否则控件会叠加到一起
            // mX = mRight;
            position.left = mLeft;
            position.top = mTop;
            position.right = mRight;
            position.bottom = mBottom;
            map.put(child, position);
        }
        setMeasuredDimension(mWidth, mBottom + getPaddingBottom());
//        super.onMeasure(widthMeasureSpec, mBottom + getPaddingBottom());
    }



    @Override
    protected LayoutParams generateDefaultLayoutParams () {
        return new LayoutParams(1, 1); // default of 1px spacing
    }

    @Override
    protected void onLayout (boolean changed, int l, int t, int r, int b) {
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            Position pos = map.get(child);
            if (pos != null) {
                child.layout(pos.left, pos.top, pos.right, pos.bottom);
            } else {
            }
        }
    }

    private class Position {
        int left, top, right, bottom;
    }

    public int getPosition (int IndexInRow, int childIndex) {
        if (IndexInRow > 0) {
            return getPosition(IndexInRow - 1, childIndex - 1) + getChildAt(childIndex - 1).getMeasuredWidth() + dividerCol;
        }
        return getPaddingLeft();
    }
    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px (Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
